package com.ll.sender;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ll.constants.ServerType;
import com.ll.exception.UserException;
import com.ll.exception.UserExceptionConstants;
import com.ll.sender.impl.ExchangeSend;
import com.ll.sender.impl.SmtpSend;
import com.ll.utils.DesUtil;
import com.ll.vo.response.EmailMessageResponseVo;

/**
 * 发送邮件
 *
 * @author liudawei
 * @date 2016年2月2日下午7:13:10
 */
public class EmailSenderTask implements Runnable {

	private static final Logger LOGGER = LoggerFactory.getLogger(EmailSenderTask.class);

	private EmailMessageResponseVo emailMessageResponseVo;

	public EmailSenderTask(EmailMessageResponseVo emailMessageResponseVo) {
		this.emailMessageResponseVo = emailMessageResponseVo;
	}

	@Override
	public void run() {
		String username = emailMessageResponseVo.getEmailServerResponseVo().getAccount();
		String smtpAddress = emailMessageResponseVo.getEmailServerResponseVo().getSmtpAddress();
		Integer port = emailMessageResponseVo.getEmailServerResponseVo().getPort();
		String password="";
		try {
			password = DesUtil.decrypt(emailMessageResponseVo.getEmailServerResponseVo().getPassword(), username);
		} catch (IOException e) {
			LOGGER.error("密码解密出错");
			throw new UserException(UserExceptionConstants.ADDRESSEXCEPTION, e);
		} catch (Exception e) {
			LOGGER.error("密码解密出错");
			throw new UserException(UserExceptionConstants.ADDRESSEXCEPTION, e);
		}
		SendEmailFactory sendEmailFactory =null;
		/**
		 * EXchange发送邮件
		 */
		if (emailMessageResponseVo.getEmailServerResponseVo().getServerType()==ServerType.SMTP.ordinal()) {
			sendEmailFactory= new SmtpSend();
		} else {
			sendEmailFactory = new ExchangeSend();
		}
		sendEmailFactory.send(smtpAddress,port, username, password, emailMessageResponseVo.getReceiver(),
				emailMessageResponseVo.getSubject(), emailMessageResponseVo.getContent());
	}

	public EmailMessageResponseVo getEmailMessageResponseVo() {
		return emailMessageResponseVo;
	}

}
